package app.auto.runner.base.http;

import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import app.auto.runner.base.ActivityStack;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.intf.ValueCallback;
import app.auto.runner.base.intf.json.JsonToMapUtils;
import app.auto.runner.base.utility.ShareAlert;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by hp on 2017/6/19.
 */

public class OkHttpClientHelper {
    public static String part;

    public static void setPart(String part) {
        OkHttpClientHelper.part = part;
    }

    public static String post(String url, MapBuilder mapBuilder) throws Exception {
        if (!url.contains("http")) {
            url = part + url;
        }
        Map map = mapBuilder.get();
        String json = JsonToMapUtils.mapToJson(map);
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();

        Response response = client.newCall(request).execute();

        return response.body().string();
//        JSONObject jsonObject = JSONObject.fromObject(json2);
//
//        String uriAPI = url;
//        /*建立HTTP Post连线*/
//        HttpPost httpRequest = new HttpPost(uriAPI);
//        //Post运作传送变数必须用NameValuePair[]阵列储存
//        //传参数 服务端获取的方法为request.getParameter("name")
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        Map m = mapBuilder.get();
//        for (Object o : m.keySet()) {
//            params.add(new BasicNameValuePair(o.toString(), m.get(o.toString()).toString()));
//        }
//        UrlEncodedFormEntity UrlEncodedFormEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
//
//        //发出HTTP request
//        httpRequest.setEntity(UrlEncodedFormEntity);
//        //取得HTTP response
//        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
//
//        //若状态码为200 ok
//        if (httpResponse.getStatusLine().getStatusCode() == 200) {
//            //取出回应字串
//            String strResult = EntityUtils.toString(httpResponse.getEntity());
//            return strResult;
//        }
//
//        return "error:" + httpResponse.getStatusLine().getStatusCode();
    }

    public static String get(String url, MapBuilder mapBuilder) throws Exception {
        if (!url.contains("http")) {
            url = part + url;
        }
        String uriAPI = url;
        /*建立HTTP Post连线*/
        //Post运作传送变数必须用NameValuePair[]阵列储存
        //传参数 服务端获取的方法为request.getParameter("name")
        Map m = mapBuilder.get();
        String params = "";
        for (Object o : m.keySet()) {
            params += "&" + o.toString() + "=" + m.get(o.toString());
        }
        if (params.length() > 0) {
            params = "?" + params.substring(1);
        }
        HttpGet httpRequest = new HttpGet(uriAPI + params);
        //发出HTTP request
        //取得HTTP response
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

        //若状态码为200 ok
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            //取出回应字串
            String strResult = EntityUtils.toString(httpResponse.getEntity());
            return strResult;
        } else {
            return httpResponse.getStatusLine().getStatusCode() + "";
        }

    }

    public static boolean toastflag = true;

    public static void call(final String visitway, final String url, final MapBuilder m, final ValueCallback funClk) {
        funClk.setUrl(url);
        funClk.setParamsMap(m.get());
        new Thread() {
            @Override
            public void run() {
                super.run();
                String rt = null;
                Exception error = null;
                try {
                    if (visitway.equals("post")) {
                        rt = OkHttpClientHelper.post(url, m);

                    } else if (visitway.equals("get")) {
                        rt = get(url, m);
                    }
                } catch (Exception e) {
                    error = e;
                    e.printStackTrace();
                }

                if (rt == null) {
                    if (toastflag) {
//                        ShareAlert.shareAlert(ActivityStack.publicactivity, url, m.get().toString(), error.getMessage(), "");
                    }
                } else {
                    rt = rt.replaceAll("\\r", "").replaceAll("\\n", "");
                    if (rt.trim().isEmpty()) {
                        if (toastflag) {
                            ShareAlert.shareAlert(ActivityStack.publicactivity, url, m.get().toString(), "返回空字符串", "");
                        }
                    } else {
                        final String finalRt = rt;
                        new android.os.Handler(Looper.getMainLooper(), new android.os.Handler.Callback() {

                            @Override
                            public boolean handleMessage(Message msg) {
                                funClk.onCallback(finalRt, null);

                                return false;
                            }
                        }).sendEmptyMessage(0);
                    }
                }
            }
        }.start();
        if (true) {
            return;
        }
        StringBuffer sb = new StringBuffer();
        Map map = m.get();
        for (Object key : map.keySet()) {
            sb.append("&" + key.toString() + "=" + map.get(key.toString()));
        }
        final MediaType FORM_CONTENT_TYPE
                = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, sb.toString().substring(1));
        Request reqt = null;
        Request req;
        if (visitway.toLowerCase().equals("post")) {
            reqt = new Request.Builder()
                    .url(url).post(requestBody)
                    .build();

        } else if (visitway.toLowerCase().equals("get")) {
            reqt = new Request.Builder()
                    .url(OkHttpClientHelper.getUrl(url, m.get()))
                    .build();
        }


        OkHttpClientHelper.getOkHttpClient().newCall(reqt).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                if (funClk != null) {
                    funClk.onFailure(e, null);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                String res = response.body().string();
                funClk.onCallback(response, null);
//                if (!response.body().toString().contains("000")) {
//                    ShareAlert.shareAlert(ActivityBaseCompat.publicactivity, url, m.toString(), response.body().toString(), "");
//                }
            }

        });
    }

    public static final String tag = "OkHttpClient";

    public static final MediaType JPEG = MediaType.parse("image/jpeg");

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static String HOST_TEST = "http://106.14.139.5:7002";
    public static String HOST_OFFICIAL = "https://gz.fromfuture.cn";
    public static String HOST = HOST_TEST;

    public static String API = "/chis/ROOT_CHIS/rcall.jsp";

    private static OkHttpClient okHttpClient;

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(new MyInterceptor())
                    .build();
        }
        return okHttpClient;
    }


    public static void upload(String path, String url, String mime, MapBuilder mapBuilder) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f = new File(path);
        if (f != null) {
            builder.addFormDataPart("file", f.getName(), RequestBody.create(MediaType.parse(mime), f));
        }
        //添加其它信息

//        builder.addFormDataPart("time",takePicTime);
//        builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude());
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        MyOkhttpUtils.getMyOkhttpInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


            }
        });
    }

    /**
     * 把参数拼接成GET请求的URL
     *
     * @param host   接口地址
     * @param params 请求参数
     * @return
     */
    public static String buildUrl(@Nullable String host, Map<String, Object> params) {
        StringBuilder urlBuilder = new StringBuilder(HOST);
        urlBuilder.append(TextUtils.isEmpty(host) ? API : host);
        urlBuilder.append("?");
        for (String key : params.keySet()) {
            String value = String.valueOf(params.get(key));
            urlBuilder.append(key).append("=").append(value).append("&");
        }
        return urlBuilder.toString();
    }

    public static String getUrl(@Nullable String host, Map<String, Object> params) {
        StringBuilder urlBuilder = new StringBuilder("");
        urlBuilder.append(TextUtils.isEmpty(host) ? API : host);
        urlBuilder.append("?");
        for (String key : params.keySet()) {
            String value = String.valueOf(params.get(key));
            urlBuilder.append(key).append("=").append(value).append("&");
        }
        return urlBuilder.toString().substring(0, urlBuilder.toString().length() - 1);
    }

    static class MyInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e(tag, request.url().toString());
            Headers headers = request.headers();
            Log.e(tag, headers.toString());
            return chain.proceed(request);
        }
    }
}
